package com.imooc.miaosha.rabbitmq;

import com.imooc.miaosha.domain.MiaoshaOrder;
import com.imooc.miaosha.domain.MiaoshaUser;
import com.imooc.miaosha.redis.RedisService;
import com.imooc.miaosha.service.GoodsService;
import com.imooc.miaosha.service.MiaoshaService;
import com.imooc.miaosha.service.OrderService;
import com.imooc.miaosha.vo.GoodsVo;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class MQReceiver {

    private static Logger log = LoggerFactory.getLogger(MQReceiver.class);

    @Autowired
    RedisService redisService;

    @Autowired
    GoodsService goodsService;

    @Autowired
    OrderService orderService;

    @Autowired
    MiaoshaService miaoshaService;

    /**
     * 接收秒杀信息并进行处理
     * @param message
     */
    @RabbitListener(queues=MQConfig.MIAOSHA_QUEUE)
    public void receiveMiaosha(String message) {
        log.info("receive miaosha message:"+message);

        MiaoshaMessage mm  = RedisService.stringToBean(message, MiaoshaMessage.class);
        MiaoshaUser user = mm.getMiaoshaUser();
        long goodsId = mm.getGoodsId();

        //判断库存
        GoodsVo goods = goodsService.getGoodsVoByGoodsId(goodsId);
        int stock = goods.getMiaoshaStock();
        if(stock <= 0) {
            return;
        }

        //判断是否已经秒杀到了
        MiaoshaOrder order = orderService.getMiaoshaOrderByUserIdGoodsId(user.getId(), goodsId);
        if(order != null) {
            return;
        }

        //减库存 下订单 写入秒杀订单
        miaoshaService.miaosha(user, goods);
    }


    @RabbitListener(queues=MQConfig.QUEUE)
    public void receive(String message) {
        log.info("receive direct message:"+message);
    }

    @RabbitListener(queues=MQConfig.QUEUE1)
    public void receiveQueue1(String message) {
        log.info("receive queue1 message:"+message);
    }

    @RabbitListener(queues=MQConfig.QUEUE2)
    public void receiveQueue2(String message) {
        log.info("receive queue2 message:"+message);
    }

    @RabbitListener(queues=MQConfig.HEADERS_QUEUE)
    public void receiveHeaderQueue(byte[] message) {
        log.info("receive headers queue message:"+ new String(message));
    }


}
